<!DOCTYPE html>
<html lang="zh-Hans">
    <!-- title -->




<!-- keywords -->




<head><meta name="generator" content="Hexo 3.8.0">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="author" content="Yeungeek">
    <meta name="renderer" content="webkit">
    <meta name="copyright" content="Yeungeek">
    
    <meta name="keywords" content="hexo,hexo-theme,hexo-blog,Android,yeungeek">
    
    <meta name="description" content="It's my Androad">
    <meta http-equiv="Cache-control" content="no-cache">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Android网络编程-TCP/IP协议 · Android 沉思录</title>
    <style type="text/css">
    @font-face {
        font-family: 'Oswald-Regular';
        src: url("/font/Oswald-Regular.ttf");
    }

    body {
        margin: 0;
    }

    header,
    footer,
    .back-top,
    .sidebar,
    .container,
    .site-intro-meta,
    .toc-wrapper {
        display: none;
    }

    .site-intro {
        position: relative;
        z-index: 3;
        width: 100%;
        /* height: 50vh; */
        overflow: hidden;
    }

    .site-intro-placeholder {
        position: absolute;
        z-index: -2;
        top: 0;
        left: 0;
        width: calc(100% + 300px);
        height: 100%;
        background: repeating-linear-gradient(-45deg, #444 0, #444 80px, #333 80px, #333 160px);
        background-position: center center;
        transform: translate3d(-226px, 0, 0);
        animation: gradient-move 2.5s ease-out 0s infinite;
    }

    @keyframes gradient-move {
        0% {
            transform: translate3d(-226px, 0, 0);
        }
        100% {
            transform: translate3d(0, 0, 0);
        }
    }

</style>

    <link rel="preload" href="/css/style.css?v=20180824" as="style" onload="this.onload=null;this.rel='stylesheet'">
    <link rel="stylesheet" href="/css/mobile.css?v=20180824" media="(max-width: 980px)">
    
    <link rel="preload" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.2.5/jquery.fancybox.min.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
    
    <!-- /*! loadCSS. [c]2017 Filament Group, Inc. MIT License */
/* This file is meant as a standalone workflow for
- testing support for link[rel=preload]
- enabling async CSS loading in browsers that do not support rel=preload
- applying rel preload css once loaded, whether supported or not.
*/ -->
<script>
(function( w ){
	"use strict";
	// rel=preload support test
	if( !w.loadCSS ){
		w.loadCSS = function(){};
	}
	// define on the loadCSS obj
	var rp = loadCSS.relpreload = {};
	// rel=preload feature support test
	// runs once and returns a function for compat purposes
	rp.support = (function(){
		var ret;
		try {
			ret = w.document.createElement( "link" ).relList.supports( "preload" );
		} catch (e) {
			ret = false;
		}
		return function(){
			return ret;
		};
	})();

	// if preload isn't supported, get an asynchronous load by using a non-matching media attribute
	// then change that media back to its intended value on load
	rp.bindMediaToggle = function( link ){
		// remember existing media attr for ultimate state, or default to 'all'
		var finalMedia = link.media || "all";

		function enableStylesheet(){
			link.media = finalMedia;
		}

		// bind load handlers to enable media
		if( link.addEventListener ){
			link.addEventListener( "load", enableStylesheet );
		} else if( link.attachEvent ){
			link.attachEvent( "onload", enableStylesheet );
		}

		// Set rel and non-applicable media type to start an async request
		// note: timeout allows this to happen async to let rendering continue in IE
		setTimeout(function(){
			link.rel = "stylesheet";
			link.media = "only x";
		});
		// also enable media after 3 seconds,
		// which will catch very old browsers (android 2.x, old firefox) that don't support onload on link
		setTimeout( enableStylesheet, 3000 );
	};

	// loop through link elements in DOM
	rp.poly = function(){
		// double check this to prevent external calls from running
		if( rp.support() ){
			return;
		}
		var links = w.document.getElementsByTagName( "link" );
		for( var i = 0; i < links.length; i++ ){
			var link = links[ i ];
			// qualify links to those with rel=preload and as=style attrs
			if( link.rel === "preload" && link.getAttribute( "as" ) === "style" && !link.getAttribute( "data-loadcss" ) ){
				// prevent rerunning on link
				link.setAttribute( "data-loadcss", true );
				// bind listeners to toggle media back
				rp.bindMediaToggle( link );
			}
		}
	};

	// if unsupported, run the polyfill
	if( !rp.support() ){
		// run once at least
		rp.poly();

		// rerun poly on an interval until onload
		var run = w.setInterval( rp.poly, 500 );
		if( w.addEventListener ){
			w.addEventListener( "load", function(){
				rp.poly();
				w.clearInterval( run );
			} );
		} else if( w.attachEvent ){
			w.attachEvent( "onload", function(){
				rp.poly();
				w.clearInterval( run );
			} );
		}
	}


	// commonjs
	if( typeof exports !== "undefined" ){
		exports.loadCSS = loadCSS;
	}
	else {
		w.loadCSS = loadCSS;
	}
}( typeof global !== "undefined" ? global : this ) );
</script>

    <link rel="icon" href="/assets/favicon.ico">
    <link rel="preload" href="https://cdn.jsdelivr.net/npm/webfontloader@1.6.28/webfontloader.min.js" as="script">
    <link rel="preload" href="https://cdn.jsdelivr.net/npm/jquery@3.3.1/dist/jquery.min.js" as="script">
    <link rel="preload" href="/scripts/main.js" as="script">
    <link rel="preload" as="font" href="/font/Oswald-Regular.ttf" crossorigin>
    <link rel="preload" as="font" href="https://at.alicdn.com/t/font_327081_1dta1rlogw17zaor.woff" crossorigin>
    
    <!-- fancybox -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.2.5/jquery.fancybox.min.js" defer></script>
    <!-- 百度统计  -->
    
    <script>
        var _hmt = _hmt || [];
        (function () {
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?75ae37defe17129870bc1ba88b527367";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
        })();
    </script>
    
    <!-- 谷歌统计  -->
    
    <script>
        (function (i, s, o, g, r, a, m) {
        i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
        (i[r].q = i[r].q || []).push(arguments)
        }, i[r].l = 1 * new Date(); a = s.createElement(o),
        m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
        })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
        ga('create', 'UA-37469819-1', 'auto');
        ga('send', 'pageview');
    </script>
    
</head>

    
        <body class="post-body">
    
    
<header class="header">

    <div class="read-progress"></div>
    <div class="header-sidebar-menu">&#xe775;</div>
    <!-- post页的toggle banner  -->
    
    <div class="banner">
            <div class="blog-title">
                <a href="/">Android 沉思录</a>
            </div>
            <div class="post-title">
                <a href="#" class="post-name">Android网络编程-TCP/IP协议</a>
            </div>
    </div>
    
    <a class="home-link" href="/">Android 沉思录</a>
</header>
    <div class="wrapper">
        <div class="site-intro" style="







height:40vh;
">
    
    <!-- 主页  -->
    
    
    <!-- 404页  -->
            
    <div class="site-intro-placeholder"></div>
    <div class="site-intro-img" style="background-image: url(/intro/post-bg.jpg)"></div>
    <div class="site-intro-meta">
        <!-- 标题  -->
        <h1 class="intro-title">
            <!-- 主页  -->
            
            Android网络编程-TCP/IP协议
            <!-- 404 -->
            
        </h1>
        <!-- 副标题 -->
        <p class="intro-subtitle">
            <!-- 主页副标题  -->
            
            
            <!-- 404 -->
            
        </p>
        <!-- 文章页meta -->
        
            <div class="post-intros">
                <!-- 文章页标签  -->
                
                    <div class="post-intro-tags">
    
        <a class="post-tag" href="javascript:void(0);" data-tags="Network">Network</a>
    
        <a class="post-tag" href="javascript:void(0);" data-tags="TCP">TCP</a>
    
        <a class="post-tag" href="javascript:void(0);" data-tags="UDP">UDP</a>
    
        <a class="post-tag" href="javascript:void(0);" data-tags="IP">IP</a>
    
</div>
                
                
                    <div class="post-intro-read">
                        <span>字数统计: <span class="post-count word-count">2.3k</span>阅读时长: <span class="post-count reading-time">8 min</span></span>
                    </div>
                
                <div class="post-intro-meta">
                    <span class="post-intro-calander iconfont-archer">&#xe676;</span>
                    <span class="post-intro-time">2019/06/21</span>
                    
                    <span id="busuanzi_container_page_pv" class="busuanzi-pv">
                        <span class="iconfont-archer">&#xe602;</span>
                        <span id="busuanzi_value_page_pv"></span>
                    </span>
                    
                    <span class="shareWrapper">
                        <span class="iconfont-archer shareIcon">&#xe71d;</span>
                        <span class="shareText">Share</span>
                        <ul class="shareList">
                            <li class="iconfont-archer share-qr" data-type="qr">&#xe75b;
                                <div class="share-qrcode"></div>
                            </li>
                            <li class="iconfont-archer" data-type="weibo">&#xe619;</li>
                            <li class="iconfont-archer" data-type="qzone">&#xe62e;</li>
                            <li class="iconfont-archer" data-type="twitter">&#xe634;</li>
                            <li class="iconfont-archer" data-type="facebook">&#xe67a;</li>
                        </ul>
                    </span>
                </div>
            </div>
        
    </div>
</div>
        <script>
 
  // get user agent
  var browser = {
    versions: function () {
      var u = window.navigator.userAgent;
      return {
        userAgent: u,
        trident: u.indexOf('Trident') > -1, //IE内核
        presto: u.indexOf('Presto') > -1, //opera内核
        webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
        gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
        mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
        ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
        android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
        iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者安卓QQ浏览器
        iPad: u.indexOf('iPad') > -1, //是否为iPad
        webApp: u.indexOf('Safari') == -1, //是否为web应用程序，没有头部与底部
        weixin: u.indexOf('MicroMessenger') == -1, //是否为微信浏览器
        uc: u.indexOf('UCBrowser') > -1 //是否为android下的UC浏览器
      };
    }()
  }
  console.log("userAgent:" + browser.versions.userAgent);

  // callback
  function fontLoaded() {
    console.log('font loaded');
    if (document.getElementsByClassName('site-intro-meta')) {
      document.getElementsByClassName('intro-title')[0].classList.add('intro-fade-in');
      document.getElementsByClassName('intro-subtitle')[0].classList.add('intro-fade-in');
      var postIntros = document.getElementsByClassName('post-intros')[0]
      if (postIntros) {
        postIntros.classList.add('post-fade-in');
      }
    }
  }

  // UC不支持跨域，所以直接显示
  function asyncCb(){
    if (browser.versions.uc) {
      console.log("UCBrowser");
      fontLoaded();
    } else {
      WebFont.load({
        custom: {
          families: ['Oswald-Regular']
        },
        loading: function () {  //所有字体开始加载
          // console.log('loading');
        },
        active: function () {  //所有字体已渲染
          fontLoaded();
        },
        inactive: function () { //字体预加载失败，无效字体或浏览器不支持加载
          console.log('inactive: timeout');
          fontLoaded();
        },
        timeout: 5000 // Set the timeout to two seconds
      });
    }
  }

  function asyncErr(){
    console.warn('script load from CDN failed, will load local script')
  }

  // load webfont-loader async, and add callback function
  function async(u, cb, err) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (cb) { o.addEventListener('load', function (e) { cb(null, e); }, false); }
    if (err) { o.addEventListener('error', function (e) { err(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }

  var asyncLoadWithFallBack = function(arr, success, reject) {
      var currReject = function(){
        reject()
        arr.shift()
        if(arr.length)
          async(arr[0], success, currReject)
        }

      async(arr[0], success, currReject)
  }

  asyncLoadWithFallBack([
    "https://cdn.jsdelivr.net/npm/webfontloader@1.6.28/webfontloader.min.js", 
    "https://cdn.bootcss.com/webfont/1.6.28/webfontloader.js",
    "/lib/webfontloader.min.js"
  ], asyncCb, asyncErr)
</script>        
        <img class="loading" src="/assets/loading.svg" style="display: block; margin: 6rem auto 0 auto; width: 6rem; height: 6rem;" />
        <div class="container container-unloaded">
            <main class="main post-page">
    <article class="article-entry">
        <p>在<a href="/2019/06/14/Network-Basic/">Android网络编程-计算机网络基础</a>一文中得知，IP协议属于网络层，TCP、UDP协议属于传输层。<br>IP协议是TCP/IP协议族的动力，它为上层协议提供无状态、无连接、不可靠的服务。<br>TCP协议是面向连接的传输层协议，提供一种面向连接的、可靠的字节流服务。<br>UDP协议是面向无连接的传输层协议，提供面向事务的简单不可靠信息传输服务。</p>
<a id="more"></a>
<h1 id="数据报文"><a href="#数据报文" class="headerlink" title="数据报文"></a>数据报文</h1><p>在不同层传输的数据单位名称不同，在网络层传输的叫数据报，在传输层传输的叫报文段。</p>
<h2 id="IP数据报"><a href="#IP数据报" class="headerlink" title="IP数据报"></a>IP数据报</h2><p>IP数据报格式如下图:<br><a href="https://imgchr.com/i/ZkNR7d" target="_blank" rel="noopener"><img src="https://s2.ax1x.com/2019/06/24/ZkNR7d.jpg" alt="IP数据报"></a><br>各个字段的详细说明：</p>
<table>
<thead>
<tr>
<th align="left">名称</th>
<th align="left">长度</th>
<th align="left">说明</th>
</tr>
</thead>
<tbody><tr>
<td align="left">版本</td>
<td align="left">4bit</td>
<td align="left">IP协议的版本，目前的IP协议版本号为4，下一代IP协议版本号为6</td>
</tr>
<tr>
<td align="left">首部长度</td>
<td align="left">4bit</td>
<td align="left">IP报头的长度，最大长度60字节(15*4)，<br>分为固定部分的长度(20字节)和可变部分的长度</td>
</tr>
<tr>
<td align="left">服务类型</td>
<td align="left">8bit</td>
<td align="left">Type Of Service</td>
</tr>
<tr>
<td align="left">总长度</td>
<td align="left">16bit</td>
<td align="left">IP报文的总长度。数据报的最大长度为 65535 字节</td>
</tr>
<tr>
<td align="left">标识</td>
<td align="left">16bit</td>
<td align="left">它是一个计数器，用来产生数据报的标识。<br>当IP报文长度超过传输网络的MTU（最大传输单元）时必须分片，<br>此标识表示同一个数据报的分片。</td>
</tr>
<tr>
<td align="left">标志</td>
<td align="left">3bit</td>
<td align="left">R、DF、MF三位，目前只有后两位有效。<br>DF位：为1表示不分片，为0表示分片。<br>MF：为1表示“更多的片”，为0表示这是最后一片。</td>
</tr>
<tr>
<td align="left">片偏移</td>
<td align="left">13bit</td>
<td align="left">本分片在原先数据报文中相对首位的偏移位。<br>片偏移以8个字节为偏移单位。</td>
</tr>
<tr>
<td align="left">生存时间</td>
<td align="left">8bit</td>
<td align="left">TTL (Time To Live)表示数据报在网络中的寿命，其单位为秒。<br>在目前的实际应用中，常以“跳”为单位。</td>
</tr>
<tr>
<td align="left">协议</td>
<td align="left">8bit</td>
<td align="left">指出IP报文携带的数据使用的哪种协议，<br>以便目的主机的IP层能知道要将数据报上交到哪个进程。<br>TCP的协议号为6，UDP的协议号为17。<br>ICMP的协议号为1，IGMP的协议号为2.</td>
</tr>
<tr>
<td align="left">首部校验和</td>
<td align="left">16bit</td>
<td align="left">计算IP头部的校验和，检查IP报头的完整性。</td>
</tr>
<tr>
<td align="left">源地址</td>
<td align="left">32bit</td>
<td align="left">标识IP数据报的源端设备。</td>
</tr>
<tr>
<td align="left">目的地址</td>
<td align="left">32bit</td>
<td align="left">标识IP数据报的目的地址。</td>
</tr>
<tr>
<td align="left">可选字段</td>
<td align="left">长度可变</td>
<td align="left">1～40 字节，用于增加IP数据报的控制功能。</td>
</tr>
<tr>
<td align="left">填充</td>
<td align="left"></td>
<td align="left">保证IP首部长度是4字节的整倍数</td>
</tr>
</tbody></table>
<h2 id="TCP报文"><a href="#TCP报文" class="headerlink" title="TCP报文"></a>TCP报文</h2><p><a href="https://imgchr.com/i/Zkc0N8" target="_blank" rel="noopener"><img src="https://s2.ax1x.com/2019/06/24/Zkc0N8.md.png" alt="TCP报文"></a></p>
<table>
<thead>
<tr>
<th align="left">名称</th>
<th align="left">长度</th>
<th align="left">说明</th>
</tr>
</thead>
<tbody><tr>
<td align="left">源端口</td>
<td align="left">16bit</td>
<td align="left">数据发送方的端口号</td>
</tr>
<tr>
<td align="left">目的端口</td>
<td align="left">16bit</td>
<td align="left">数据接受方的端口号</td>
</tr>
<tr>
<td align="left">序号</td>
<td align="left">32bit</td>
<td align="left">本数据报文中的的第一个字节的序号<br>(在数据流中每个字节都对应一个序号)</td>
</tr>
<tr>
<td align="left">确认号</td>
<td align="left">32bit</td>
<td align="left">希望收到的下一个数据报文中的第一个字节的序号</td>
</tr>
<tr>
<td align="left">数据偏移</td>
<td align="left">4bit</td>
<td align="left">表示本报文数据段距离报文段有多远</td>
</tr>
<tr>
<td align="left">保留字段</td>
<td align="left">6bit</td>
<td align="left">保留为今后使用，但目前应置为0</td>
</tr>
<tr>
<td align="left">紧急比特URG</td>
<td align="left"></td>
<td align="left">当值为1时表示次报文段中有需要紧急处理</td>
</tr>
<tr>
<td align="left">确认比特ACK</td>
<td align="left"></td>
<td align="left">值为1时确认号有效，值为0时确认号无效</td>
</tr>
<tr>
<td align="left">复位比特RST</td>
<td align="left"></td>
<td align="left">值为1时表示TCP连接存在严重的错误，需要重新进行连接</td>
</tr>
<tr>
<td align="left">同步比特SYN</td>
<td align="left"></td>
<td align="left">值为1表示这是一个连接请求或连接接受报文</td>
</tr>
<tr>
<td align="left">终止比特FIN</td>
<td align="left"></td>
<td align="left">值为1表示要发送的数据报已经发送完毕，需要释放传送连接</td>
</tr>
<tr>
<td align="left">窗口</td>
<td align="left">16bit</td>
<td align="left">TCP连接的一端根据缓存空间的大小来确定自己接受窗口的大小<br>限制发送放的窗口上限</td>
</tr>
<tr>
<td align="left">检验和</td>
<td align="left">16bit</td>
<td align="left">用来检验首部和数据两部分的正确性</td>
</tr>
<tr>
<td align="left">紧急指针字段</td>
<td align="left">16bit</td>
<td align="left">紧急指针指出在本报文段中的紧急数据的最后一个字节的序号</td>
</tr>
<tr>
<td align="left">选项字段</td>
<td align="left">长度可变</td>
<td align="left">TCP 首部可以有多达40字节的可选信息，<br>用于把附加信息传递给终点，或用来对齐其它选项</td>
</tr>
</tbody></table>
<h2 id="UDP报文"><a href="#UDP报文" class="headerlink" title="UDP报文"></a>UDP报文</h2><p>相对于TCP报文，UDP报文简单了很多。<br><img src="https://s2.ax1x.com/2019/06/24/ZEKjVP.png" alt="UDP报文"></p>
<table>
<thead>
<tr>
<th align="left">名称</th>
<th align="left">长度</th>
<th align="left">说明</th>
</tr>
</thead>
<tbody><tr>
<td align="left">源端口</td>
<td align="left">16bit</td>
<td align="left">数据发送方的端口号</td>
</tr>
<tr>
<td align="left">目的端口</td>
<td align="left">16bit</td>
<td align="left">数据接受方的端口号</td>
</tr>
<tr>
<td align="left">包长度</td>
<td align="left">16bit</td>
<td align="left">UDP首部的长度和数据的长度之和。单位为字节</td>
</tr>
<tr>
<td align="left">校验和</td>
<td align="left">16bit</td>
<td align="left">用来检验首部和数据两部分的正确性</td>
</tr>
</tbody></table>
<h1 id="TCP三次握手和四次挥手"><a href="#TCP三次握手和四次挥手" class="headerlink" title="TCP三次握手和四次挥手"></a>TCP三次握手和四次挥手</h1><p>TCP用三次握手来创建连接，使用四次分手来释放连接。<br><a href="https://imgchr.com/i/ZEMwMd" target="_blank" rel="noopener"><img src="https://s2.ax1x.com/2019/06/24/ZEMwMd.md.png" alt="三次握手"></a></p>
<h2 id="三次握手"><a href="#三次握手" class="headerlink" title="三次握手"></a>三次握手</h2><p>三次握手的目的是同步连接双方的序列号和确认号并交换TCP窗口大小的信息。<br>握手过程：</p>
<blockquote>
<ol>
<li>第一次握手：建立连接，客户端先发送连接请求报文，将SYN设置为1，Sequence Number为x。客户端进入SYN+SEND状态，等待服务器确认。</li>
<li>第二次握手：服务器收到SYN报文。服务器收到客户端的SYN报文，需要对这个SYN报文进行确认，设置Acknowledgment Number为x+1(Sequence+1)；同时，自己还要送法SYN消息，将SYN位置为1，Sequence Number为y；服务器将上述所有信息放到一个报文段(即SYN+ACK报文段)中，一并发送给客户端，此时服务器进入SYN+RECV状态。</li>
<li>第三次握手：客户端收到服务器的 SYN+ACK报文段。然后将Acknowlegment Number设为y+1,向服务器发送ACK报文段，这个报文段发送完毕后，客户端端服务器都进入ESTABLISHED状态，完成TCP三次握手。</li>
</ol>
</blockquote>
<p>完成了三次握手，客户端和服务器就可以开始传送数据了。</p>
<h2 id="四次挥手"><a href="#四次挥手" class="headerlink" title="四次挥手"></a>四次挥手</h2><p>当客户端和服务端传输数据完毕后，需要断开TCP连接。TCP断开的过程，就是四次挥手。</p>
<blockquote>
<ol>
<li>第一次挥手：客户端(也可以是服务器)，设置Sequence Number和Acknowledgment Number，向服务器发送一个FIN报文段。此时客户端进入FIN_WAIT_1状态；这表示客户端没有数据发送给主机了。</li>
<li>第二次挥手：服务器收到客户端发来的FIN报文段，向客户端回一个ACK报文段，Acknowledgement Number为Sequence Number加1；客户端进入FIN_WAIT_2状态，服务器进入CLOSE_WAIT状态；服务器告诉客户端，我同意你的”关闭”请求。</li>
<li>第三次挥手：服务器向客户端发送FIN报文段，请求关闭连接，同时服务器进入LAST_ACK状态。</li>
<li>第四次挥手：客户端收到服务器发送的FIN报文段，向主机发送ACK报文段，然后客户端进入TIME_WAIT状态，服务器收到客户端的ACK报文段以后，就关闭连接，此时，客户端等待2MSL后一次没有到收到回复，则证明服务端已正常关闭，那好，客户端也可以关闭连接了。</li>
</ol>
</blockquote>
<h2 id="TCP三次握手的必要性"><a href="#TCP三次握手的必要性" class="headerlink" title="TCP三次握手的必要性"></a>TCP三次握手的必要性</h2><p>防止服务器端因接收了早已失效的连接请求报文，从而一直等待客户端请求，最终导致形成死锁、浪费资源。</p>
<h2 id="TCP四次挥手的必要性"><a href="#TCP四次挥手的必要性" class="headerlink" title="TCP四次挥手的必要性"></a>TCP四次挥手的必要性</h2><p>为了保证通信双方都能通知对方，需释放、断开连接。</p>
<h3 id="为什么客户端关闭连接前要等待2MSL时间"><a href="#为什么客户端关闭连接前要等待2MSL时间" class="headerlink" title="为什么客户端关闭连接前要等待2MSL时间"></a>为什么客户端关闭连接前要等待2MSL时间</h3><blockquote>
<p>MSL: 最大报文段生存时间</p>
</blockquote>
<p>四个报文发送完毕后，就可以直接进入CLOSE状态了，但是有可能网络是不可靠的，一切都可能发生，比如有可能最后一个ACK丢失。所以TIME_WAIT状态是用来重发可能丢失的ACK报文。展开具体来讲：  </p>
<ul>
<li>为了保证客户端发送的最后1个连接释放确认报文 能到达服务器，从而使得服务器能正常释放连接。</li>
<li>防止早已失效的连接请求报文，出现在本连接中。客户端发送了最后1个连接释放请求确认报文后，再经过2MSL时间，则可使本连接持续时间内所产生的所有报文段都从网络中消失。</li>
</ul>
<h1 id="TCP、UDP比较"><a href="#TCP、UDP比较" class="headerlink" title="TCP、UDP比较"></a>TCP、UDP比较</h1><table>
<thead>
<tr>
<th align="left"></th>
<th align="left">TCP</th>
<th align="left">UDP</th>
</tr>
</thead>
<tbody><tr>
<td align="left">可靠性</td>
<td align="left">可靠</td>
<td align="left">不可靠</td>
</tr>
<tr>
<td align="left">连接性</td>
<td align="left">面向连接</td>
<td align="left">无连接</td>
</tr>
<tr>
<td align="left">报文</td>
<td align="left">面向字节流</td>
<td align="left">面向报文</td>
</tr>
<tr>
<td align="left">效率</td>
<td align="left">低效</td>
<td align="left">高效</td>
</tr>
<tr>
<td align="left">双工性</td>
<td align="left">全双工</td>
<td align="left">一对一，一对多，多对一，多对多<br>支持多播和广播</td>
</tr>
<tr>
<td align="left">流量控制</td>
<td align="left">滑动窗口机制</td>
<td align="left"></td>
</tr>
<tr>
<td align="left">拥塞控制</td>
<td align="left">慢开始/拥塞避免<br>快重传/快恢复</td>
<td align="left"></td>
</tr>
<tr>
<td align="left">传输速度</td>
<td align="left">慢</td>
<td align="left">快</td>
</tr>
<tr>
<td align="left">应用场景</td>
<td align="left">效率要求相对低，准确要求相对高。<br>要求有连接的场景</td>
<td align="left">效率要求相对高，准确要求相对低</td>
</tr>
<tr>
<td align="left">应用</td>
<td align="left">SMTP，TELNET，HTTP，FTP</td>
<td align="left">DNS，RIP，NFS，SNMP，<br>IP电话，流媒体</td>
</tr>
</tbody></table>
<h1 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h1><ul>
<li><a href="https://www.jianshu.com/p/65605622234b" target="_blank" rel="noopener">计算机网络：这是一份全面 &amp; 详细 的TCP协议攻略</a></li>
<li><a href="https://www.cnblogs.com/edisonchou/p/5987827.html" target="_blank" rel="noopener">《图解TCP/IP》读书笔记</a></li>
<li><a href="https://juejin.im/post/5a2614b8f265da432652af7d" target="_blank" rel="noopener">Android网络编程：基础理论汇总</a></li>
</ul>

    </article>
    <!-- license  -->
    
        <div class="license-wrapper">
            <p>原文作者：<a href="http://yeungeek.github.io">Yeungeek</a>
            </p><p>原文链接：<a href="http://yeungeek.github.io/2019/06/21/Network-TCP-IP/">http://yeungeek.github.io/2019/06/21/Network-TCP-IP/</a>
            </p><p>发表日期：<a href="http://yeungeek.github.io/2019/06/21/Network-TCP-IP/">June 21st 2019, 11:28:07 am</a>
            </p><p>更新日期：<a href="http://yeungeek.github.io/2019/06/21/Network-TCP-IP/">January 17th 2020, 3:44:17 am</a>
            </p><p>版权声明：本文采用<a rel="license" href="http://creativecommons.org/licenses/by-nc/4.0/">知识共享署名-非商业性使用 4.0 国际许可协议</a>进行许可</p>
        </div>
    
    <!-- paginator  -->
    <ul class="post-paginator">
        <li class="next">
            
                <div class="nextSlogan">Next Post</div>
                <a href="/2019/06/26/Network-Socket/" title="Android网络编程-Socket">
                    <div class="nextTitle">Android网络编程-Socket</div>
                </a>
            
        </li>
        <li class="previous">
            
                <div class="prevSlogan">Previous Post</div>
                <a href="/2019/06/14/Network-Basic/" title="Android网络编程-计算机网络基础">
                    <div class="prevTitle">Android网络编程-计算机网络基础</div>
                </a>
            
        </li>
    </ul>
    <!-- 评论插件 -->
    <!-- 来必力City版安装代码 -->

    <div id="lv-container" data-id="city" data-uid="MTAyMC8yODIyNi80Nzk4">
        <script type="text/javascript">
            (function (d, s) {
                var j, e = d.getElementsByTagName(s)[0];
                if (typeof LivereTower === 'function') { return; }
                j = d.createElement(s);
                j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
                j.async = true;

                e.parentNode.insertBefore(j, e);
            })(document, 'script');
        </script>
        <noscript>为正常使用来必力评论功能请激活JavaScript</noscript>
    </div>

<!-- City版安装代码已完成 -->
    
    
    <!-- partial('_partial/comment/changyan') -->
    <!--PC版-->


    
    

    <!-- 评论 -->
</main>
            <!-- profile -->
            
        </div>
        <footer class="footer footer-unloaded">
    <!-- social  -->
    
    <div class="social">
        
    
        
            
                <a href="mailto:yeungeek@gmail.com" class="iconfont-archer email" title="email"></a>
            
        
    
        
            
                <a href="//github.com/yeungeek" class="iconfont-archer github" target="_blank" title="github"></a>
            
        
    
        
            
                <span class="iconfont-archer wechat" title="wechat">
                  
                  <img class="profile-qr" src="/assets/wechat_qr.jpeg">
                </span>
            
        
    
        
    
        
    
        
            
                <a href="//weibo.com/springyounger" class="iconfont-archer weibo" target="_blank" title="weibo"></a>
            
        
    
        
    
        
    
        
    
        
            
                <a href="//twitter.com/yeungeek" class="iconfont-archer twitter" target="_blank" title="twitter"></a>
            
        
    
        
    
        
            
                <a href="//stackoverflow.com/users/943667/yeungeek" class="iconfont-archer stack-overflow" target="_blank" title="stack-overflow"></a>
            
        
    
        
            
                <a href="//segmentfault.com/u/yeungeek" class="iconfont-archer segmentFault" target="_blank" title="segmentFault"></a>
            
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
            
                <a href="/atom.xml" class="iconfont-archer rss" target="_blank" title="rss"></a>
            
        
    

    </div>
    
    <!-- powered by Hexo  -->
    <div class="copyright">
        <span id="hexo-power">Powered by <a href="https://hexo.io/" target="_blank">Hexo</a></span><span class="iconfont-archer power">&#xe635;</span><span id="theme-info">theme <a href="https://github.com/fi3ework/hexo-theme-archer" target="_blank">Archer</a></span>
    </div>
    <!-- 不蒜子  -->
    
    <div class="busuanzi-container">
    
     
    <span id="busuanzi_container_site_pv">PV: <span id="busuanzi_value_site_pv"></span> :)</span>
    
    </div>
    
</footer>
    </div>
    <!-- toc -->
    
    <div class="toc-wrapper" style=
    







top:40vh;

    >
        <div class="toc-catalog">
            <span class="iconfont-archer catalog-icon">&#xe613;</span><span>CATALOG</span>
        </div>
        <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#数据报文"><span class="toc-number">1.</span> <span class="toc-text">数据报文</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#IP数据报"><span class="toc-number">1.1.</span> <span class="toc-text">IP数据报</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#TCP报文"><span class="toc-number">1.2.</span> <span class="toc-text">TCP报文</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#UDP报文"><span class="toc-number">1.3.</span> <span class="toc-text">UDP报文</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#TCP三次握手和四次挥手"><span class="toc-number">2.</span> <span class="toc-text">TCP三次握手和四次挥手</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#三次握手"><span class="toc-number">2.1.</span> <span class="toc-text">三次握手</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#四次挥手"><span class="toc-number">2.2.</span> <span class="toc-text">四次挥手</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#TCP三次握手的必要性"><span class="toc-number">2.3.</span> <span class="toc-text">TCP三次握手的必要性</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#TCP四次挥手的必要性"><span class="toc-number">2.4.</span> <span class="toc-text">TCP四次挥手的必要性</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#为什么客户端关闭连接前要等待2MSL时间"><span class="toc-number">2.4.1.</span> <span class="toc-text">为什么客户端关闭连接前要等待2MSL时间</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#TCP、UDP比较"><span class="toc-number">3.</span> <span class="toc-text">TCP、UDP比较</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#参考"><span class="toc-number">4.</span> <span class="toc-text">参考</span></a></li></ol>
    </div>
    
    <div class="back-top iconfont-archer">&#xe639;</div>
    <div class="sidebar sidebar-hide">
    <ul class="sidebar-tabs sidebar-tabs-active-0">
        <li class="sidebar-tab-archives"><span class="iconfont-archer">&#xe67d;</span><span class="tab-name">Archive</span></li>
        <li class="sidebar-tab-tags"><span class="iconfont-archer">&#xe61b;</span><span class="tab-name">Tag</span></li>
        <li class="sidebar-tab-categories"><span class="iconfont-archer">&#xe666;</span><span class="tab-name">Cate</span></li>
    </ul>
    <div class="sidebar-content sidebar-content-show-archive">
          <div class="sidebar-panel-archives">
    <!-- 在ejs中将archive按照时间排序 -->
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    <div class="total-and-search">
        <div class="total-archive">
        Total : 12
        </div>
        <!-- search  -->
        
    </div>
    
    <div class="post-archive">
    
    
    
    
    <div class="archive-year"> 2020 </div>
    <ul class="year-list">
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">01/17</span><a class="archive-post-title" href="/2020/01/17/AndroidCamera-UsingCamera1/">Android Camera-Camera1使用</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">01/14</span><a class="archive-post-title" href="/2020/01/14/AndroidCamera-Basic/">Android Camera-基础知识篇</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">01/13</span><a class="archive-post-title" href="/2020/01/13/AndroidCamera-Series/">Android Camera-系列文章</a>
        </li>
    
    
    
    
    
        </ul>
    
    <div class="archive-year"> 2019 </div>
    <ul class="year-list">
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">08/21</span><a class="archive-post-title" href="/2019/08/21/AndroidNDK-DeepUnderstandJNI/">Android NDK-深入理解JNI</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">07/25</span><a class="archive-post-title" href="/2019/07/25/Network-Retrofit/">Android网络编程-Retrofit源码角度分析Http</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">07/17</span><a class="archive-post-title" href="/2019/07/17/Network-OKHttp/">Android网络编程-OKHttp源码角度分析Http</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">07/15</span><a class="archive-post-title" href="/2019/07/15/Network-Cookie-Session-Token/">Android网络编程-Cookie，Session，Token</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">07/12</span><a class="archive-post-title" href="/2019/07/12/Network-Http/">Android网络编程-HTTP/HTTPS</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">06/26</span><a class="archive-post-title" href="/2019/06/26/Network-Socket/">Android网络编程-Socket</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">06/21</span><a class="archive-post-title" href="/2019/06/21/Network-TCP-IP/">Android网络编程-TCP/IP协议</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">06/14</span><a class="archive-post-title" href="/2019/06/14/Network-Basic/">Android网络编程-计算机网络基础</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">06/13</span><a class="archive-post-title" href="/2019/06/13/Network-Series/">Android网络编程-系列文章</a>
        </li>
    
    </ul></div>
  </div>
        <div class="sidebar-panel-tags">
    <div class="sidebar-tags-name">
    
        <span class="sidebar-tag-name" data-tags="Camera"><span class="iconfont-archer">&#xe606;</span>Camera</span>
    
        <span class="sidebar-tag-name" data-tags="Camera2"><span class="iconfont-archer">&#xe606;</span>Camera2</span>
    
        <span class="sidebar-tag-name" data-tags="CameraX"><span class="iconfont-archer">&#xe606;</span>CameraX</span>
    
        <span class="sidebar-tag-name" data-tags="JNI"><span class="iconfont-archer">&#xe606;</span>JNI</span>
    
        <span class="sidebar-tag-name" data-tags="NDK"><span class="iconfont-archer">&#xe606;</span>NDK</span>
    
        <span class="sidebar-tag-name" data-tags="Network"><span class="iconfont-archer">&#xe606;</span>Network</span>
    
        <span class="sidebar-tag-name" data-tags="Session"><span class="iconfont-archer">&#xe606;</span>Session</span>
    
        <span class="sidebar-tag-name" data-tags="Cookie"><span class="iconfont-archer">&#xe606;</span>Cookie</span>
    
        <span class="sidebar-tag-name" data-tags="Token"><span class="iconfont-archer">&#xe606;</span>Token</span>
    
        <span class="sidebar-tag-name" data-tags="Android"><span class="iconfont-archer">&#xe606;</span>Android</span>
    
        <span class="sidebar-tag-name" data-tags="Http"><span class="iconfont-archer">&#xe606;</span>Http</span>
    
        <span class="sidebar-tag-name" data-tags="Https"><span class="iconfont-archer">&#xe606;</span>Https</span>
    
        <span class="sidebar-tag-name" data-tags="OKHttp"><span class="iconfont-archer">&#xe606;</span>OKHttp</span>
    
        <span class="sidebar-tag-name" data-tags="Retrofit"><span class="iconfont-archer">&#xe606;</span>Retrofit</span>
    
        <span class="sidebar-tag-name" data-tags="Socket"><span class="iconfont-archer">&#xe606;</span>Socket</span>
    
        <span class="sidebar-tag-name" data-tags="TCP"><span class="iconfont-archer">&#xe606;</span>TCP</span>
    
        <span class="sidebar-tag-name" data-tags="UDP"><span class="iconfont-archer">&#xe606;</span>UDP</span>
    
        <span class="sidebar-tag-name" data-tags="IP"><span class="iconfont-archer">&#xe606;</span>IP</span>
    
    </div>
    <div class="iconfont-archer sidebar-tags-empty">&#xe678;</div>
    <div class="tag-load-fail" style="display: none; color: #ccc; font-size: 0.6rem;">
    缺失模块。<br>
    1、请确保node版本大于6.2<br>
    2、在博客根目录（注意不是archer根目录）执行以下命令：<br>
    <span style="color: #f75357; font-size: 1rem; line-height: 2rem;">npm i hexo-generator-json-content --save</span><br>
    3、在根目录_config.yml里添加配置：
    <pre style="color: #787878; font-size: 0.6rem;">
jsonContent:
  meta: false
  pages: false
  posts:
    title: true
    date: true
    path: true
    text: false
    raw: false
    content: false
    slug: false
    updated: false
    comments: false
    link: false
    permalink: false
    excerpt: false
    categories: true
    tags: true</pre>
    </div> 
    <div class="sidebar-tags-list"></div>
</div>
        <div class="sidebar-panel-categories">
    <div class="sidebar-categories-name">
    
        <span class="sidebar-category-name" data-categories="Camera"><span class="iconfont-archer">&#xe60a;</span>Camera</span>
    
        <span class="sidebar-category-name" data-categories="Android框架层"><span class="iconfont-archer">&#xe60a;</span>Android框架层</span>
    
        <span class="sidebar-category-name" data-categories="Android应用层"><span class="iconfont-archer">&#xe60a;</span>Android应用层</span>
    
    </div>
    <div class="iconfont-archer sidebar-categories-empty">&#xe678;</div>
    <div class="sidebar-categories-list"></div>
</div>
    </div>
</div> 
    <script>
    var siteMeta = {
        root: "/",
        author: "Yeungeek"
    }
</script>
    <!-- CDN failover -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.3.1/dist/jquery.min.js"></script>
    <script type="text/javascript">
        if (typeof window.$ === 'undefined')
        {
            console.warn('jquery load from jsdelivr failed, will load local script')
            document.write('<script src="/lib/jquery.min.js">\x3C/script>')
        }
    </script>
    <script src="/scripts/main.js"></script>
    <!-- algolia -->
    
    <!-- busuanzi  -->
    
    <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    
    <!-- CNZZ  -->
    
    </div>
    <!-- async load share.js -->
    
        <script src="/scripts/share.js" async></script>    
     
    </body>
</html>


